﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using WebSocket4Net;
using WinCustomsService.Model;

namespace WinCustomsService
{
   public class Customs179Job : ISyncData
    {
        public void SyncData()
        {
          
            GetPushDetails();
          
          
        }
        public void GetPushDetails()
        {
            long id = 0;
            CustomsPushPayInfo pushPayInfoModel = HttpClientHelper.GetCustomsPush(out id);
            if(!string.IsNullOrEmpty(pushPayInfoModel.sessionID))
                SignAndUpload179V3(pushPayInfoModel,id);
        }


        /// <summary>
        /// 179
        /// </summary>
        private void SignAndUpload179(CustomsPushPayInfo pushPayInfoModel,long id)
        {
            try
            {
             
                var setting = HttpClientHelper.GetSetting();
              
                CustomsPushInfo customsPush = new CustomsPushInfo();
               
                customsPush.SessionID = pushPayInfoModel.sessionID;

                string strPayExchangeInfoHeadJson = JsonConvert.SerializeObject(pushPayInfoModel.payExchangeInfoHead);
                string strPayExchangeInfoHead = $"\"payExchangeInfoHead\":\"{strPayExchangeInfoHeadJson}\"";
                string strPostPayExchangeInfoHead = $"\"payExchangeInfoHead\":{strPayExchangeInfoHeadJson}";
                string strPayExchangeInfoListsJson = JsonConvert.SerializeObject(pushPayInfoModel.payExchangeInfoLists);
                string strPayExchangeInfoLists = $"\"payExchangeInfoLists\":\"{strPayExchangeInfoListsJson}\"";
                string strPostPayExchangeInfoLists = $"\"payExchangeInfoLists\":{strPayExchangeInfoListsJson}";

                StringBuilder PostJson = new StringBuilder();
                string pushPayInfoStr = $"\"sessionID\":\"{pushPayInfoModel.sessionID}\"||{strPayExchangeInfoHead}||{strPayExchangeInfoLists}||\"serviceTime\":\"{pushPayInfoModel.serviceTime}\"";
               
                var websocket = new WebSocket("ws://127.0.0.1:61232");
                websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>((sender, e) =>
                {
                    websocket.Close();
                    customsPush.Message = e.Exception.Message.Trim();
                    HttpClientHelper.UpdateSignError(customsPush);

                });

                websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>((sender, e) =>
                {
                    var message = e.Message.Trim();
                    var errorMessage = Regex.Match(message, @"Error"":\[(\S+)\]").Groups[1].Value;
                    if(message.Contains("握手成功"))
                    {
                        string strSendData = "{\"_method\":\"cus-sec_SpcSignDataAsPEM\",\"_id\":" + id + ",\"args\":{\"inData\":\"" + pushPayInfoStr.Replace("\"", "\\\"") + "\",\"passwd\":\"" + setting.Passwd + "\"}}";
                        websocket.Send(strSendData);
                    }
                    else if(errorMessage.Length > 0)
                    {
                        LogHelper.WriteLog("加签错误:" );

                        // 加签错误
                        websocket.Close();
                        customsPush.Message = errorMessage;
                        HttpClientHelper.UpdateSignError(customsPush);
                    }
                    else
                    {
                        // 加签正确
                        websocket.Close();
                        pushPayInfoModel.signValue = Regex.Match(message, @"Data"":\[""(\S+?)""").Groups[1].Value;
                      
                        HttpClientHelper.UploadCustomsPushPay(pushPayInfoModel);
                    }
                });
                websocket.Open();
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("签名", ex);
            }
            
        }


        private void SignAndUpload179V3(CustomsPushPayInfo pushPayInfoModel, long id)
        {
            try
            {
                var setting = HttpClientHelper.GetSetting();
                CustomsPushInfo customsPush = new CustomsPushInfo();
                customsPush.SessionID = pushPayInfoModel.sessionID;

                string payExchangeInfoHead = JsonConvert.SerializeObject(pushPayInfoModel.payExchangeInfoHead);
                payExchangeInfoHead = payExchangeInfoHead.Replace("\\\"", "\"");
                LogHelper.WriteLog("payExchangeInfoHead:"+ payExchangeInfoHead);
                string payExchangeInfoLists = JsonConvert.SerializeObject(pushPayInfoModel.payExchangeInfoLists);
 
                string inData = $"\"sessionID\":\"{pushPayInfoModel.sessionID}\"||\"payExchangeInfoHead\":\"{payExchangeInfoHead}\"||\"payExchangeInfoLists\":\"{payExchangeInfoLists}\"||\"serviceTime\":\"{pushPayInfoModel.serviceTime}\"";
                LogHelper.WriteLog("inData:" + inData);
                string strSendData2 = "{\"_method\":\"cus-sec_SpcSignDataAsPEM\",\"_id\":" + id + ",\"args\":{\"inData\":\"" + inData.Replace("\"", "\\\"") + "\",\"passwd\":\"" + setting.Passwd + "\"}}";
                LogHelper.WriteLog("inData2:" + strSendData2);
                var websocket = new WebSocket("ws://127.0.0.1:61232");
                websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>((sender, e) =>
                {
                    websocket.Close();
                    customsPush.Message = e.Exception.Message.Trim();
                    HttpClientHelper.UpdateSignError(customsPush);

                });

                websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>((sender, e) =>
                {
                    var message = e.Message.Trim();
                    var errorMessage = Regex.Match(message, @"Error"":\[(\S+)\]").Groups[1].Value;
                    if(message.Contains("握手成功"))
                    {
                        string strSendData = "{\"_method\":\"cus-sec_SpcSignDataAsPEM\",\"_id\":" + id + ",\"args\":{\"inData\":\"" + inData + "\",\"passwd\":\"" + setting.Passwd + "\"}}";
                        websocket.Send(strSendData);
                    }
                    else if(errorMessage.Length > 0)
                    {
                        LogHelper.WriteLog("加签错误:");

                        // 加签错误
                        websocket.Close();
                        customsPush.Message = errorMessage;
                        HttpClientHelper.UpdateSignError(customsPush);
                    }
                    else
                    {
                        // 加签正确
                        websocket.Close();
                        pushPayInfoModel.signValue = Regex.Match(message, @"Data"":\[""(\S+?)""").Groups[1].Value;

                        HttpClientHelper.UploadCustomsPushPay(pushPayInfoModel);
                    }
                });
                websocket.Open();
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("签名", ex);
            }

        }
    }
}
